<?php
/**
 * Created by PhpStorm.
 * User: Monkey
 * Date: 2021/10/13
 * Time: 11:27
 * Desc: 登录
 */
declare (strict_types=1);

namespace app\api\controller;

use app\api\base\controller\Base;

use app\api\validate\LoginValidate;
use think\facade\Cache;

class Login extends Base
{
    /**
     * 登录
     */
    public function index()
    {
        if (request()->isPost()) {
            $validate = new LoginValidate();
            $ret = $validate->scene('index')->check(input());
            if(!$ret){
                return json(_E($validate->getError()));
            }

            $account = input('account', '');
            $password = input('password', '');

            $userInfo = \app\extend\model\User::where([
                ['account|mobile','=',$account],
                ['is_delete','=',0],
            ])->field('id,account,mobile,password,salt,is_delete')->find();

            if (empty($userInfo) || $userInfo->password != password($password, $userInfo->salt)) {
                return json(_E('账号或密码输入错误'));
            }

            \app\extend\model\User::where([
                ['id','=',$userInfo->id]
            ])->update([
                'ip' => getClientIp(),
                'last_logined_at' => date('Y-m-d H:i:s')
            ]);

            //生成token
            $token = md5($userInfo->id.'_'.$userInfo->mobile.'_'.random(4).'_'.time());

            Cache::set($token, $userInfo->id,7 * 24 * 3600);

            return json(_S('登录成功',[
                'token' => $token
            ]));
        }
    }

    /**
     * 退出
     */
    public function logout()
    {
        Cache::delete(self::$UserInfo['token']);

        return json(_S('退出成功'));
    }
}
